/*
 * Copyright (c) 2011. This file is public under GPLv3 license.
 * For more information about license please refer to http://www.gnu.org/licenses/gpl.html
 */

package com.freetools.watchdog.commands;

import com.freetools.watchdog.exceptions.ParametersErrorException;
import com.freetools.watchdog.model.CommandName;
import com.freetools.watchdog.model.IModelHolder;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Date: Feb 15, 2011
 *
 * @author Michael Morozov
 */
@CommandName("query")
public class QueryCmd extends Command
{

    public void execute(IModelHolder model) throws ParametersErrorException
    {
        checkParameters();
        Matcher matcher = Pattern.compile("from records where (.*)\\s?(?:order by)?").matcher(model.getQuery());
        if (matcher.find())
        {

            StringBuilder sb = new StringBuilder(model.getQuery());
            sb.delete(matcher.start(1), matcher.end(1)).insert(matcher.start(1), getParameters().get(0));
            model.setQuery(sb.toString());
        }
    }
}
